package com.fzs.sshd.thread;

import com.fzs.sshd.cli.server.session.SessionManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.sshd.common.session.Session;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Iterator;
import java.util.List;

@Slf4j
@EnableScheduling
@Configuration
public class ThreadPoolManager {

    /**
     * 定时线程池
     */
    @Scheduled(cron = "0 0/1 * * * ?")
    public void clearExpSession() {
        String expTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"));
        log.info("定时任务启动...{}", expTime);
        List<Session> sessions = SessionManager.expSessionMap.get(expTime);
        if (sessions != null) {
            Iterator<Session> iterator = sessions.iterator();
            while (iterator.hasNext()) {
                Session session = iterator.next();
                if (session.isOpen()) {
                    log.info("定时任务执行...{}", expTime);
                    session.close(false);
                }
                iterator.remove();
            }
            if (sessions.isEmpty()) {
                SessionManager.expSessionMap.remove(expTime);
            }
        }
    }
}
